import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

/**
 * 操作类型枚举
 */
export enum OperationType {
  DELETE_FILE = 'delete_file',
  DELETE_FOLDER = 'delete_folder',
  RENAME_FILE = 'rename_file',
  RENAME_FOLDER = 'rename_folder',
  MOVE_FILE = 'move_file',
  MOVE_FOLDER = 'move_folder',
  CREATE_FOLDER = 'create_folder'
}

/**
 * 操作记录接口
 */
export interface OperationRecord {
  id: string
  type: OperationType
  timestamp: number
  description: string
  data: any
  undoHandler: () => Promise<void>
}

/**
 * 操作历史管理组合式函数
 */
export function useOperationHistory() {
  const history = ref<OperationRecord[]>([])
  const maxHistorySize = 20 // 最多保存20个操作记录

  /**
   * 添加操作记录
   */
  const addOperation = (operation: Omit<OperationRecord, 'id' | 'timestamp'>) => {
    const record: OperationRecord = {
      ...operation,
      id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
      timestamp: Date.now()
    }

    history.value.unshift(record)

    // 限制历史记录数量
    if (history.value.length > maxHistorySize) {
      history.value = history.value.slice(0, maxHistorySize)
    }

    console.log('添加操作记录:', record.description)
  }

  /**
   * 撤销最近的操作
   */
  const undoLastOperation = async () => {
    if (history.value.length === 0) {
      ElMessage.warning('没有可撤销的操作')
      return
    }

    const lastOperation = history.value[0]
    
    try {
      await lastOperation.undoHandler()
      
      // 从历史记录中移除已撤销的操作
      history.value.shift()
      
      ElMessage.success(`已撤销: ${lastOperation.description}`)
      console.log('撤销操作成功:', lastOperation.description)
      
    } catch (error) {
      console.error('撤销操作失败:', error)
      ElMessage.error('撤销操作失败')
    }
  }

  /**
   * 清空操作历史
   */
  const clearHistory = () => {
    history.value = []
    console.log('操作历史已清空')
  }

  /**
   * 获取最近的操作描述
   */
  const getLastOperationDescription = () => {
    return history.value.length > 0 ? history.value[0].description : null
  }

  /**
   * 检查是否有可撤销的操作
   */
  const canUndo = () => {
    return history.value.length > 0
  }

  return {
    history: readonly(history),
    addOperation,
    undoLastOperation,
    clearHistory,
    getLastOperationDescription,
    canUndo
  }
}

/**
 * 文件操作撤销辅助函数
 */
export function createFileOperationHandlers() {
  const { addOperation, undoLastOperation, canUndo, getLastOperationDescription } = useOperationHistory()

  /**
   * 创建删除文件的撤销操作
   */
  const createDeleteFileUndo = (file: any, restoreHandler: () => Promise<void>) => {
    addOperation({
      type: OperationType.DELETE_FILE,
      description: `删除文件: ${file.originalName}`,
      data: { file },
      undoHandler: restoreHandler
    })
  }

  /**
   * 创建删除文件夹的撤销操作
   */
  const createDeleteFolderUndo = (folder: any, restoreHandler: () => Promise<void>) => {
    addOperation({
      type: OperationType.DELETE_FOLDER,
      description: `删除文件夹: ${folder.originalName}`,
      data: { folder },
      undoHandler: restoreHandler
    })
  }

  /**
   * 创建重命名的撤销操作
   */
  const createRenameUndo = (item: any, oldName: string, newName: string, restoreHandler: () => Promise<void>) => {
    const itemType = item.isDirectory ? '文件夹' : '文件'
    addOperation({
      type: item.isDirectory ? OperationType.RENAME_FOLDER : OperationType.RENAME_FILE,
      description: `重命名${itemType}: ${oldName} → ${newName}`,
      data: { item, oldName, newName },
      undoHandler: restoreHandler
    })
  }

  /**
   * 创建移动的撤销操作
   */
  const createMoveUndo = (item: any, fromFolder: string, toFolder: string, restoreHandler: () => Promise<void>) => {
    const itemType = item.isDirectory ? '文件夹' : '文件'
    addOperation({
      type: item.isDirectory ? OperationType.MOVE_FOLDER : OperationType.MOVE_FILE,
      description: `移动${itemType}: ${item.originalName} (${fromFolder} → ${toFolder})`,
      data: { item, fromFolder, toFolder },
      undoHandler: restoreHandler
    })
  }

  /**
   * 创建新建文件夹的撤销操作
   */
  const createCreateFolderUndo = (folder: any, deleteHandler: () => Promise<void>) => {
    addOperation({
      type: OperationType.CREATE_FOLDER,
      description: `创建文件夹: ${folder.originalName}`,
      data: { folder },
      undoHandler: deleteHandler
    })
  }

  return {
    createDeleteFileUndo,
    createDeleteFolderUndo,
    createRenameUndo,
    createMoveUndo,
    createCreateFolderUndo,
    undoLastOperation,
    canUndo,
    getLastOperationDescription
  }
}

// 修复readonly导入
import { readonly } from 'vue'
